<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>用户管理后台</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Arial', sans-serif;
        }

        body {
            padding: 15px;
            background-color: #f5f5f5;
            font-size: 14px;
        }

        .container {
            width: 100%;
            max-width: 100%;
            margin: 0 auto;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 15px;
            overflow-x: auto;
        }

        .header-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        h1 {
            text-align: center;
            margin-bottom: 15px;
            color: #333;
            font-size: 18px;
            flex: 1;
        }

        .logout-btn {
            padding: 8px 16px;
            background-color: #f44336;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
        }

        .logout-btn:hover {
            background-color: #d32f2f;
        }

        .tabs {
            display: flex;
            margin-bottom: 15px;
            border-bottom: 1px solid #ddd;
        }

        .tab {
            padding: 10px 20px;
            cursor: pointer;
            border: none;
            background: none;
            font-size: 14px;
            color: #666;
            border-bottom: 2px solid transparent;
            transition: all 0.3s;
        }

        .tab.active {
            color: #2196F3;
            border-bottom-color: #2196F3;
            font-weight: bold;
        }

        .tab:hover {
            color: #2196F3;
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        .header-section {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            flex-wrap: wrap;
        }

        .stats-container {
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
        }

        .stat-item {
            padding: 8px 12px;
            border-radius: 4px;
            background-color: #f2f2f2;
            font-size: 14px;
        }

        .stat-total {
            background-color: #e3f2fd;
        }

        .stat-success {
            background-color: #e8f5e9;
            color: #2e7d32;
        }

        .stat-fail {
            background-color: #ffebee;
            color: #c62828;
        }

        .stat-pending {
            background-color: #fff8e1;
            color: #f57f17;
        }

        .refresh-btn {
            padding: 8px 16px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }

        .refresh-btn:hover {
            background-color: #45a049;
        }

        .add-btn {
            padding: 8px 16px;
            background-color: #2196F3;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            margin-left: 10px;
        }

        .add-btn:hover {
            background-color: #1976D2;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            min-width: 600px;
        }

        th, td {
            padding: 10px 8px;
            text-align: left;
            border-bottom: 1px solid #ddd;
            font-size: 13px;
        }

        th {
            background-color: #f2f2f2;
            font-weight: bold;
            position: sticky;
            top: 0;
        }

        tr:hover {
            background-color: #f9f9f9;
        }

        .status-0 {
            color: #4CAF50;
            font-weight: bold;
        }

        .status-1 {
            color: #f44336;
            font-weight: bold;
        }

        .status-2 {
            color: #FF9800;
            font-weight: bold;
        }

        .action-btn {
            padding: 5px 10px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            margin-left: 5px;
            transition: all 0.3s;
        }

        .action-btn:hover {
            opacity: 0.8;
        }

        .success-btn {
            background-color: #4CAF50;
            color: white;
        }

        .fail-btn {
            background-color: #f44336;
            color: white;
        }

        .edit-btn {
            background-color: #FF9800;
            color: white;
        }

        .delete-btn {
            padding: 5px 10px;
            background-color: #607d8b;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            margin-left: 5px;
        }

        .delete-btn:hover {
            background-color: #455a64;
        }

        .action-buttons {
            display: flex;
            gap: 5px;
        }

        .message {
            margin-top: 15px;
            padding: 10px;
            border-radius: 5px;
            text-align: center;
            font-size: 14px;
            display: none;
        }

        .success {
            background-color: #d4edda;
            color: #155724;
            display: block;
        }

        .error {
            background-color: #f8d7da;
            color: #721c24;
            display: block;
        }

        .summary {
            margin-top: 15px;
            padding: 10px;
            background-color: #f8f9fa;
            border-radius: 5px;
            font-size: 14px;
        }

        /* 新增样式：手机号可复制样式 */
        .copyable {
            cursor: pointer;
            position: relative;
            display: inline-block;
            transition: all 0.2s;
        }

        .copyable:hover {
            color: #2196F3;
            text-decoration: underline;
        }

        .copyable.copied::after {
            content: '✓ 已复制';
            position: absolute;
            top: -20px;
            left: 50%;
            transform: translateX(-50%);
            background-color: #4CAF50;
            color: white;
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 11px;
            white-space: nowrap;
            z-index: 10;
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }

        .modal-content {
            background-color: white;
            margin: 5% auto;
            padding: 20px;
            border-radius: 8px;
            width: 90%;
            max-width: 500px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.2);
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #ddd;
        }

        .modal-title {
            font-size: 18px;
            font-weight: bold;
            color: #333;
        }

        .close {
            color: #aaa;
            font-size: 24px;
            font-weight: bold;
            cursor: pointer;
        }

        .close:hover {
            color: #333;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #333;
        }

        .form-input {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }

        .form-input:focus {
            outline: none;
            border-color: #2196F3;
        }

        .form-actions {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 20px;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }

        .btn-primary {
            background-color: #2196F3;
            color: white;
        }

        .btn-primary:hover {
            background-color: #1976D2;
        }

        .btn-secondary {
            background-color: #6c757d;
            color: white;
        }

        .btn-secondary:hover {
            background-color: #545b62;
        }

        @media (max-width: 768px) {
            body {
                padding: 10px;
            }

            .container {
                padding: 10px;
                border-radius: 6px;
            }

            h1 {
                font-size: 16px;
                margin-bottom: 12px;
            }

            .tabs {
                flex-wrap: wrap;
            }

            .tab {
                padding: 8px 12px;
                font-size: 13px;
            }

            .header-section {
                flex-direction: column;
                align-items: flex-start;
                gap: 10px;
            }

            .stats-container {
                width: 100%;
                justify-content: space-between;
            }

            .stat-item {
                font-size: 12px;
                padding: 6px 8px;
            }

            .refresh-btn, .add-btn {
                width: 100%;
                margin-left: 0;
                margin-top: 5px;
            }

            th, td {
                padding: 8px 6px;
                font-size: 12px;
            }

            .action-btn, .delete-btn {
                padding: 4px 8px;
                font-size: 11px;
            }

            .action-buttons {
                flex-direction: column;
                gap: 3px;
            }

            /* 移动端调整复制提示位置 */
            .copyable.copied::after {
                top: -18px;
                font-size: 10px;
            }

            .modal-content {
                margin: 10% auto;
                width: 95%;
                padding: 15px;
            }
        }

        ::-webkit-scrollbar {
            height: 6px;
            width: 6px;
        }

        ::-webkit-scrollbar-thumb {
            background-color: #ccc;
            border-radius: 3px;
        }

        ::-webkit-scrollbar-track {
            background-color: #f1f1f1;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="header-bar">
        <h1>用户管理后台</h1>
        <button id="logoutBtn" class="logout-btn">退出登录</button>
    </div>
    
    <!-- 标签页 -->
    <div class="tabs">
        <button class="tab active" data-tab="users">用户管理</button>
        <button class="tab" data-tab="promoters">推广员管理</button>
        <button class="tab" data-tab="promotion-stats">推广统计</button>
    </div>

    <!-- 用户管理标签页 -->
    <div class="tab-content active" id="users-tab">
        <div class="header-section">
            <div class="stats-container">
                <div class="stat-item stat-total" id="totalUsers">总计: 0</div>
                <div class="stat-item stat-success" id="successUsers">成功: 0</div>
                <div class="stat-item stat-fail" id="failUsers">失败: 0</div>
                <div class="stat-item stat-pending" id="pendingUsers">未处理: 0</div>
            </div>
            <div>
                <button id="refreshBtn" class="refresh-btn">手动刷新</button>
            </div>
        </div>
        <div style="overflow-x: auto;">
            <table id="userTable">
                <thead>
                <tr>
                    <th>序号</th>
                    <th>手机号</th>
                    <th>验证码</th>
                    <th>邀请码</th>
                    <th>推广人</th>
                    <th>状态</th>
                    <th>注册时间</th>
                    <th>验证码提交时间</th>
                    <th>处理时间</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="userTableBody">
                <!-- 数据将通过JavaScript动态填充 -->
                </tbody>
            </table>
        </div>
        <div class="summary" id="dataSummary">
            最后更新时间: <span id="lastUpdateTime">-</span>
        </div>
    </div>

    <!-- 推广员管理标签页 -->
    <div class="tab-content" id="promoters-tab">
        <div class="header-section">
            <div class="stats-container">
                <div class="stat-item stat-total" id="totalPromoters">推广员总数: 0</div>
            </div>
            <div>
                <button id="refreshPromotersBtn" class="refresh-btn">刷新</button>
                <button id="addPromoterBtn" class="add-btn">添加推广员</button>
            </div>
        </div>
        <div style="overflow-x: auto;">
            <table id="promoterTable">
                <thead>
                <tr>
                    <th>ID</th>
                    <th>用户名</th>
                    <th>推广码</th>
                    <th>上级ID</th>
                    <th>邮箱</th>
                    <th>创建时间</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="promoterTableBody">
                <!-- 数据将通过JavaScript动态填充 -->
                </tbody>
            </table>
        </div>
        <div class="summary" id="promoterSummary">
            最后更新时间: <span id="lastPromoterUpdateTime">-</span>
        </div>
    </div>

    <!-- 推广统计标签页 -->
    <div class="tab-content" id="promotion-stats-tab">
        <div class="header-section">
            <div class="stats-container">
                <div class="stat-item stat-total" id="totalPromotionStats">推广统计总数: 0</div>
            </div>
            <div>
                <button id="refreshPromotionStatsBtn" class="refresh-btn">刷新统计</button>
            </div>
        </div>
        <div style="overflow-x: auto;">
            <table id="promotionStatsTable">
                <thead>
                <tr>
                    <th>推广码</th>
                    <th>推广员</th>
                    <th>总用户数</th>
                    <th>成功用户</th>
                    <th>失败用户</th>
                    <th>未处理用户</th>
                    <th>成功率</th>
                </tr>
                </thead>
                <tbody id="promotionStatsTableBody">
                <!-- 数据将通过JavaScript动态填充 -->
                </tbody>
            </table>
        </div>
        <div class="summary" id="promotionStatsSummary">
            最后更新时间: <span id="lastPromotionStatsUpdateTime">-</span>
        </div>
    </div>

    <div id="message" class="message"></div>
</div>

<!-- 添加/编辑推广员模态框 -->
<div id="promoterModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 class="modal-title" id="modalTitle">添加推广员</h3>
            <span class="close">&times;</span>
        </div>
        <form id="promoterForm">
            <div class="form-group">
                <label class="form-label" for="username">用户名</label>
                <input type="text" id="username" class="form-input" required>
            </div>
            <div class="form-group">
                <label class="form-label" for="password">密码</label>
                <input type="password" id="password" class="form-input" required>
            </div>
            <div class="form-group">
                <label class="form-label" for="promotionCode">推广码</label>
                <input type="text" id="promotionCode" class="form-input" required>
            </div>
            <div class="form-group">
                <label class="form-label" for="parentId">上级ID</label>
                <input type="number" id="parentId" class="form-input" value="0">
            </div>
            <div class="form-group">
                <label class="form-label" for="email">邮箱</label>
                <input type="email" id="email" class="form-input">
            </div>
            <div class="form-actions">
                <button type="button" class="btn btn-secondary" id="cancelBtn">取消</button>
                <button type="submit" class="btn btn-primary" id="saveBtn">保存</button>
            </div>
        </form>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        // 用户管理相关变量
        const userTableBody = document.getElementById('userTableBody');
        const refreshBtn = document.getElementById('refreshBtn');
        const messageDiv = document.getElementById('message');
        const totalUsersEl = document.getElementById('totalUsers');
        const successUsersEl = document.getElementById('successUsers');
        const failUsersEl = document.getElementById('failUsers');
        const pendingUsersEl = document.getElementById('pendingUsers');
        const lastUpdateTimeEl = document.getElementById('lastUpdateTime');

        // 推广员管理相关变量
        const promoterTableBody = document.getElementById('promoterTableBody');
        const refreshPromotersBtn = document.getElementById('refreshPromotersBtn');
        const addPromoterBtn = document.getElementById('addPromoterBtn');
        const totalPromotersEl = document.getElementById('totalPromoters');
        const lastPromoterUpdateTimeEl = document.getElementById('lastPromoterUpdateTime');

        // 推广统计相关变量
        const promotionStatsTableBody = document.getElementById('promotionStatsTableBody');
        const refreshPromotionStatsBtn = document.getElementById('refreshPromotionStatsBtn');
        const totalPromotionStatsEl = document.getElementById('totalPromotionStats');
        const lastPromotionStatsUpdateTimeEl = document.getElementById('lastPromotionStatsUpdateTime');

        // 模态框相关变量
        const promoterModal = document.getElementById('promoterModal');
        const modalTitle = document.getElementById('modalTitle');
        const promoterForm = document.getElementById('promoterForm');
        const closeBtn = document.querySelector('.close');
        const cancelBtn = document.getElementById('cancelBtn');

        // 标签页相关变量
        const tabs = document.querySelectorAll('.tab');
        const tabContents = document.querySelectorAll('.tab-content');

        // 退出登录按钮
        const logoutBtn = document.getElementById('logoutBtn');

        let refreshInterval;
        let currentUsers = [];
        let currentPromoters = [];
        let currentPromotionStats = [];
        let editingPromoter = null;
        let currentUser = null;

        // 检查登录状态和权限
        function checkLoginStatus() {
            const userInfo = localStorage.getItem('userInfo');
            if (!userInfo) {
                window.location.href = 'login.html';
                return;
            }

            currentUser = JSON.parse(userInfo);
            
            // 不再在前端隐藏标签页，后端已经处理了权限
            // 所有用户都能看到所有标签页，但操作权限由后端控制
        }

        // 初始化页面
        checkLoginStatus();
        initTabs();
        fetchUserList();
        startAutoRefresh();

        // 标签页切换功能
        function initTabs() {
            tabs.forEach(tab => {
                tab.addEventListener('click', function() {
                    const tabId = this.getAttribute('data-tab');
                    
                    // 更新标签页状态
                    tabs.forEach(t => t.classList.remove('active'));
                    this.classList.add('active');
                    
                    // 更新内容显示
                    tabContents.forEach(content => {
                        content.classList.remove('active');
                    });
                    document.getElementById(tabId + '-tab').classList.add('active');
                    
                    // 根据标签页加载相应数据
                    if (tabId === 'users') {
                        fetchUserList();
                    } else if (tabId === 'promoters') {
                        fetchPromoterList();
                    } else if (tabId === 'promotion-stats') {
                        fetchPromotionStats();
                    }
                });
            });
        }

        // 手动刷新按钮
        refreshBtn.addEventListener('click', function () {
            fetchUserList();
        });

        // 推广员刷新按钮
        refreshPromotersBtn.addEventListener('click', function () {
            fetchPromoterList();
        });

        // 添加推广员按钮
        addPromoterBtn.addEventListener('click', function () {
            openPromoterModal();
        });

        // 推广统计刷新按钮
        refreshPromotionStatsBtn.addEventListener('click', function () {
            fetchPromotionStats();
        });

        // 模态框关闭事件
        closeBtn.addEventListener('click', closePromoterModal);
        cancelBtn.addEventListener('click', closePromoterModal);
        window.addEventListener('click', function(event) {
            if (event.target === promoterModal) {
                closePromoterModal();
            }
        });

        // 表单提交事件
        promoterForm.addEventListener('submit', function(event) {
            event.preventDefault();
            savePromoter();
        });

        // 退出登录按钮事件
        logoutBtn.addEventListener('click', function() {
            logout();
        });

        // 获取用户列表
        function fetchUserList() {
            fetch('/api/admin/getUserList', {
                method: 'GET'
            })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        // 直接显示所有数据，不进行前端筛选
                        currentUsers = data.data;
                        renderUserTable(currentUsers);
                        updateStats(currentUsers);
                        updateLastUpdateTime();
                    } else {
                        showMessage('获取用户列表失败: ' + data.message, 'error');
                    }
                })
                .catch(error => {
                    showMessage('网络错误，请重试', 'error');
                    console.error('Error:', error);
                });
        }

        // 获取推广员列表
        function fetchPromoterList() {
            fetch('/api/admin/getPromoterList', {
                method: 'GET'
            })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        currentPromoters = data.data;
                        renderPromoterTable(currentPromoters);
                        updatePromoterStats(currentPromoters);
                        updatePromoterLastUpdateTime();
                    } else {
                        showMessage('获取推广员列表失败: ' + data.message, 'error');
                    }
                })
                .catch(error => {
                    showMessage('网络错误，请重试', 'error');
                    console.error('Error:', error);
                });
        }

        // 获取推广统计（使用用户列表数据在前端统计）
        function fetchPromotionStats() {
            // 使用现有的用户数据进行统计
            const stats = calculatePromotionStats(currentUsers);
            currentPromotionStats = stats;
            renderPromotionStatsTable(currentPromotionStats);
            updatePromotionStatsStats(currentPromotionStats);
            updatePromotionStatsLastUpdateTime();
        }

        // 计算推广统计数据
        function calculatePromotionStats(users) {
            const statsMap = {};
            
            // 按推广码分组统计
            users.forEach(user => {
                const promotionCode = user.promotionCode || '未知';
                const promoter = user.promoter || '未知';
                
                if (!statsMap[promotionCode]) {
                    statsMap[promotionCode] = {
                        promotionCode: promotionCode,
                        promoter: promoter,
                        totalUsers: 0,
                        successUsers: 0,
                        failUsers: 0,
                        pendingUsers: 0
                    };
                }
                
                const stat = statsMap[promotionCode];
                stat.totalUsers++;
                
                switch (user.isSuccess) {
                    case 0:
                        stat.successUsers++;
                        break;
                    case 1:
                        stat.failUsers++;
                        break;
                    case 2:
                        stat.pendingUsers++;
                        break;
                }
            });
            
            // 转换为数组并返回
            return Object.values(statsMap);
        }

        // 渲染用户表格
        function renderUserTable(users) {
            userTableBody.innerHTML = '';

            // 按创建时间倒序排列，最新的在前面
            const sortedUsers = [...users].sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));

            sortedUsers.forEach((user, index) => {
                const row = document.createElement('tr');

                // 序号 - 按时间倒序排列
                const indexCell = document.createElement('td');
                indexCell.textContent = index + 1; // 正序序号
                row.appendChild(indexCell);

                // 手机号 - 添加复制功能
                const phoneCell = document.createElement('td');
                const phoneSpan = document.createElement('span');
                phoneSpan.textContent = user.phone;
                phoneSpan.className = 'copyable';
                phoneSpan.title = '点击复制手机号';
                // 添加点击复制事件
                phoneSpan.addEventListener('click', function(event) {
                    event.stopPropagation(); // 防止事件冒泡
                    copyToClipboard(user.phone, phoneSpan);
                });
                phoneCell.appendChild(phoneSpan);
                row.appendChild(phoneCell);

                // 验证码
                const codeCell = document.createElement('td');
                codeCell.textContent = user.verificationCode || '-';
                row.appendChild(codeCell);

                // 邀请码
                const inviteCell = document.createElement('td');
                inviteCell.textContent = user.invitationCode || '-';
                row.appendChild(inviteCell);

                // 推广人
                const promoterCell = document.createElement('td');
                promoterCell.textContent = user.promoter || '-';
                row.appendChild(promoterCell);

                // 状态
                const statusCell = document.createElement('td');
                statusCell.className = `status-${user.isSuccess}`;

                let statusText = '';
                switch (user.isSuccess) {
                    case 0:
                        statusText = '成功';
                        break;
                    case 1:
                        statusText = '失败';
                        break;
                    case 2:
                        statusText = '未处理';
                        break;
                    default:
                        statusText = '未知';
                }

                statusCell.textContent = statusText;
                row.appendChild(statusCell);

                // 注册时间
                const timeCell = document.createElement('td');
                timeCell.textContent = formatDateTime(user.createdAt);
                row.appendChild(timeCell);

                // 验证码提交时间
                const submitTimeCell = document.createElement('td');
                submitTimeCell.textContent = user.submitTime ? formatDateTime(user.submitTime) : '-';
                row.appendChild(submitTimeCell);

                // 处理时间
                const processingTimeCell = document.createElement('td');
                processingTimeCell.textContent = user.processingTime ? formatDateTime(user.processingTime) : '-';
                row.appendChild(processingTimeCell);

                // 操作列
                const actionCell = document.createElement('td');
                const actionButtons = document.createElement('div');
                actionButtons.className = 'action-buttons';

                // 删除按钮
                const deleteBtn = document.createElement('button');
                deleteBtn.className = 'delete-btn';
                deleteBtn.textContent = '删除';
                deleteBtn.addEventListener('click', function() {
                    if (confirm('确定要删除此用户吗？')) {
                        deleteUser(user.id);
                    }
                });

                // 根据状态添加不同的操作按钮
                if (user.isSuccess === 2) { // 未处理状态
                    const successBtn = document.createElement('button');
                    successBtn.className = 'action-btn success-btn';
                    successBtn.textContent = '设为成功';
                    successBtn.addEventListener('click', function() {
                        updateUserStatus(user.id, user.phone, 0)
                            .then(() => fetchUserList());
                    });

                    const failBtn = document.createElement('button');
                    failBtn.className = 'action-btn fail-btn';
                    failBtn.textContent = '设为失败';
                    failBtn.addEventListener('click', function() {
                        updateUserStatus(user.id, user.phone, 1)
                            .then(() => fetchUserList());
                    });

                    actionButtons.appendChild(successBtn);
                    actionButtons.appendChild(failBtn);
                }
                else if (user.isSuccess === 1) { // 失败状态
                    const successBtn = document.createElement('button');
                    successBtn.className = 'action-btn success-btn';
                    successBtn.textContent = '设为成功';
                    successBtn.addEventListener('click', function() {
                        updateUserStatus(user.id, user.phone, 0)
                            .then(() => fetchUserList());
                    });

                    actionButtons.appendChild(successBtn);
                }

                actionButtons.appendChild(deleteBtn);
                actionCell.appendChild(actionButtons);
                row.appendChild(actionCell);

                userTableBody.appendChild(row);
            });
        }

                // 渲染推广员表格
        function renderPromoterTable(promoters) {
            promoterTableBody.innerHTML = '';

            promoters.forEach((promoter, index) => {
                const row = document.createElement('tr');

                // ID
                const idCell = document.createElement('td');
                idCell.textContent = promoter.id;
                row.appendChild(idCell);

                // 用户名
                const usernameCell = document.createElement('td');
                usernameCell.textContent = promoter.username;
                row.appendChild(usernameCell);

                // 推广码
                const codeCell = document.createElement('td');
                codeCell.textContent = promoter.promotionCode;
                row.appendChild(codeCell);

                // 上级ID
                const parentCell = document.createElement('td');
                parentCell.textContent = promoter.parentId || '0';
                row.appendChild(parentCell);

                // 邮箱
                const emailCell = document.createElement('td');
                emailCell.textContent = promoter.email || '-';
                row.appendChild(emailCell);

                // 创建时间
                const timeCell = document.createElement('td');
                timeCell.textContent = formatDateTime(promoter.createdAt);
                row.appendChild(timeCell);

                // 操作列
                const actionCell = document.createElement('td');
                const actionButtons = document.createElement('div');
                actionButtons.className = 'action-buttons';

                // 复制推广链接按钮
                const copyLinkBtn = document.createElement('button');
                copyLinkBtn.className = 'action-btn success-btn';
                copyLinkBtn.textContent = '复制链接';
                copyLinkBtn.title = '复制推广链接';
                copyLinkBtn.addEventListener('click', function() {
                    const promotionLink = `http://yx.kukudb.cn?promotionCode=${promoter.promotionCode}`;
                    copyToClipboard(promotionLink, copyLinkBtn);
                });

                // 编辑按钮
                const editBtn = document.createElement('button');
                editBtn.className = 'action-btn edit-btn';
                editBtn.textContent = '编辑';
                editBtn.addEventListener('click', function() {
                    editPromoter(promoter);
                });

                // 删除按钮
                const deleteBtn = document.createElement('button');
                deleteBtn.className = 'delete-btn';
                deleteBtn.textContent = '删除';
                deleteBtn.addEventListener('click', function() {
                    if (confirm('确定要删除此推广员吗？')) {
                        deletePromoter(promoter.username);
                    }
                });

                actionButtons.appendChild(copyLinkBtn);
                actionButtons.appendChild(editBtn);
                actionButtons.appendChild(deleteBtn);
                actionCell.appendChild(actionButtons);
                row.appendChild(actionCell);

                promoterTableBody.appendChild(row);
            });
        }

        // 复制到剪贴板功能
        function copyToClipboard(text, element) {
            // 使用现代Clipboard API
            if (navigator.clipboard && window.isSecureContext) {
                navigator.clipboard.writeText(text).then(() => {
                    showCopyFeedback(element);
                }).catch(err => {
                    // 如果现代API失败，使用传统方法
                    useFallbackCopyMethod(text, element);
                });
            } else {
                // 使用传统方法
                useFallbackCopyMethod(text, element);
            }
        }

        // 传统复制方法
        function useFallbackCopyMethod(text, element) {
            // 创建一个临时的textarea元素
            const textArea = document.createElement("textarea");
            textArea.value = text;
            textArea.style.position = "fixed";
            textArea.style.left = "-999999px";
            textArea.style.top = "-999999px";
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();

            try {
                const successful = document.execCommand('copy');
                if (successful) {
                    showCopyFeedback(element);
                } else {
                    showMessage('复制失败，请手动复制', 'error');
                }
            } catch (err) {
                showMessage('复制失败，请手动复制', 'error');
            }

            document.body.removeChild(textArea);
        }

        // 显示复制反馈
        function showCopyFeedback(element) {
            // 添加复制成功样式
            element.classList.add('copied');

            // 显示成功消息
            showMessage('手机号已复制: ' + element.textContent, 'success');

            // 2秒后移除样式
            setTimeout(() => {
                element.classList.remove('copied');
            }, 2000);
        }

        // 更新用户统计信息
        function updateStats(users) {
            const total = users.length;
            const success = users.filter(u => u.isSuccess === 0).length;
            const fail = users.filter(u => u.isSuccess === 1).length;
            const pending = users.filter(u => u.isSuccess === 2).length;

            totalUsersEl.textContent = `总计: ${total}`;
            successUsersEl.textContent = `成功: ${success}`;
            failUsersEl.textContent = `失败: ${fail}`;
            pendingUsersEl.textContent = `未处理: ${pending}`;
        }

        // 更新推广员统计信息
        function updatePromoterStats(promoters) {
            const total = promoters.length;
            totalPromotersEl.textContent = `推广员总数: ${total}`;
        }

        // 更新最后更新时间
        function updateLastUpdateTime() {
            const now = new Date();
            lastUpdateTimeEl.textContent = now.toLocaleString();
        }

        // 更新推广员最后更新时间
        function updatePromoterLastUpdateTime() {
            const now = new Date();
            lastPromoterUpdateTimeEl.textContent = now.toLocaleString();
        }

        // 渲染推广统计表格
        function renderPromotionStatsTable(stats) {
            promotionStatsTableBody.innerHTML = '';

            stats.forEach((stat, index) => {
                const row = document.createElement('tr');

                // 推广码
                const codeCell = document.createElement('td');
                codeCell.textContent = stat.promotionCode || '-';
                row.appendChild(codeCell);

                // 推广员
                const promoterCell = document.createElement('td');
                promoterCell.textContent = stat.promoter || '-';
                row.appendChild(promoterCell);

                // 总用户数
                const totalCell = document.createElement('td');
                totalCell.textContent = stat.totalUsers || 0;
                row.appendChild(totalCell);

                // 成功用户
                const successCell = document.createElement('td');
                successCell.textContent = stat.successUsers || 0;
                row.appendChild(successCell);

                // 失败用户
                const failCell = document.createElement('td');
                failCell.textContent = stat.failUsers || 0;
                row.appendChild(failCell);

                // 未处理用户
                const pendingCell = document.createElement('td');
                pendingCell.textContent = stat.pendingUsers || 0;
                row.appendChild(pendingCell);

                // 成功率
                const successRateCell = document.createElement('td');
                const total = stat.totalUsers || 0;
                const success = stat.successUsers || 0;
                let successRate = 0;
                if (total > 0) {
                    successRate = Math.round((success / total) * 100);
                }
                successRateCell.textContent = `${successRate}%`;
                successRateCell.style.fontWeight = 'bold';
                successRateCell.style.color = successRate >= 50 ? '#4CAF50' : '#f44336';
                row.appendChild(successRateCell);

                promotionStatsTableBody.appendChild(row);
            });
        }

        // 更新推广统计信息
        function updatePromotionStatsStats(stats) {
            const total = stats.length;
            totalPromotionStatsEl.textContent = `推广统计总数: ${total}`;
        }

        // 更新推广统计最后更新时间
        function updatePromotionStatsLastUpdateTime() {
            const now = new Date();
            lastPromotionStatsUpdateTimeEl.textContent = now.toLocaleString();
        }

        // 格式化日期时间
        function formatDateTime(dateString) {
            if (!dateString) return '-';
            const date = new Date(dateString);
            return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'});
        }

        // 更新用户状态（返回Promise）
        function updateUserStatus(id, phone, isSuccess) {
            const requestData = {
                id: id,
                phone: phone,
                isSuccess: isSuccess
            };

            return fetch('/api/admin/setIsSuccess', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestData)
            })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        showMessage('状态更新成功', 'success');
                        // 立即刷新用户列表以显示最新状态
                        fetchUserList();
                        return true;
                    } else {
                        showMessage('状态更新失败: ' + data.message, 'error');
                        return Promise.reject(data.message);
                    }
                })
                .catch(error => {
                    showMessage('网络错误，请重试', 'error');
                    console.error('Error:', error);
                    return Promise.reject(error);
                });
        }

        // 删除用户
        function deleteUser(id) {
            fetch('/api/admin/deleteUsers', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ id: id })
            })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        showMessage('用户删除成功', 'success');
                        fetchUserList(); // 刷新列表
                    } else {
                        showMessage('删除失败: ' + data.message, 'error');
                    }
                })
                .catch(error => {
                    showMessage('网络错误，请重试', 'error');
                    console.error('Error:', error);
                });
        }

        // 打开推广员模态框
        function openPromoterModal(promoter = null) {
            editingPromoter = promoter;
            
            if (promoter) {
                modalTitle.textContent = '编辑推广员';
                document.getElementById('username').value = promoter.username;
                document.getElementById('password').value = ''; // 编辑时不显示密码
                document.getElementById('promotionCode').value = promoter.promotionCode;
                document.getElementById('parentId').value = promoter.parentId || 0;
                document.getElementById('email').value = promoter.email || '';
                document.getElementById('username').readOnly = true; // 编辑时用户名不可修改
            } else {
                modalTitle.textContent = '添加推广员';
                promoterForm.reset();
                document.getElementById('username').readOnly = false;
            }
            
            promoterModal.style.display = 'block';
        }

        // 关闭推广员模态框
        function closePromoterModal() {
            promoterModal.style.display = 'none';
            editingPromoter = null;
            promoterForm.reset();
        }

        // 保存推广员
        function savePromoter() {
            const formData = {
                username: document.getElementById('username').value,
                password: document.getElementById('password').value,
                promotionCode: document.getElementById('promotionCode').value,
                parentId: parseInt(document.getElementById('parentId').value) || 0,
                email: document.getElementById('email').value
            };

            // 验证必填字段
            if (!formData.username || !formData.password || !formData.promotionCode) {
                showMessage('请填写所有必填字段', 'error');
                return;
            }

            const url = editingPromoter ? '/api/admin/updatePromoter' : '/api/admin/addPromoter';
            const method = 'POST';

            fetch(url, {
                method: method,
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
            })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        showMessage(editingPromoter ? '推广员更新成功' : '推广员添加成功', 'success');
                        closePromoterModal();
                        fetchPromoterList(); // 刷新列表
                    } else {
                        showMessage((editingPromoter ? '更新失败: ' : '添加失败: ') + data.message, 'error');
                    }
                })
                .catch(error => {
                    showMessage('网络错误，请重试', 'error');
                    console.error('Error:', error);
                });
        }

        // 编辑推广员
        function editPromoter(promoter) {
            openPromoterModal(promoter);
        }

        // 删除推广员
        function deletePromoter(username) {
            fetch('/api/admin/deletePromoter', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ username: username })
            })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        showMessage('推广员删除成功', 'success');
                        fetchPromoterList(); // 刷新列表
                    } else {
                        showMessage('删除失败: ' + data.message, 'error');
                    }
                })
                .catch(error => {
                    showMessage('网络错误，请重试', 'error');
                    console.error('Error:', error);
                });
        }

        // 自动刷新
        function startAutoRefresh() {
            clearInterval(refreshInterval);
            refreshInterval = setInterval(fetchUserList, 5000); // 每5秒刷新一次
        }

        // 退出登录功能
        function logout() {
            if (confirm('确定要退出登录吗？')) {
                // 清除本地存储的用户信息
                localStorage.removeItem('userInfo');
                
                // 停止自动刷新
                clearInterval(refreshInterval);
                
                // 显示退出成功消息
                showMessage('退出登录成功', 'success');
                
                // 延迟跳转到登录页面
                setTimeout(() => {
                    window.location.href = 'login.html';
                }, 1500);
            }
        }

        // 显示消息
        function showMessage(message, type) {
            messageDiv.textContent = message;
            messageDiv.className = 'message ' + type;

            // 3秒后自动消失
            setTimeout(() => {
                messageDiv.className = 'message';
            }, 3000);
        }
    });
</script>
</body>
</html>
